import { getRequestId } from '@/utils/tools'

export default {

    uploadPostDetail({ data }) {
        const db = this.database();
        const postCol = db.collection('post');

        let commentId = getRequestId()

        let postDetail = {
            ...data,
            commentId,
            postTimeStamp: new Date().getTime()
        }


        if (data) {
            console.log('uploadPostDetail', postDetail, JSON.stringify(postDetail));
            return postCol.add(postDetail);
        }
    },

    async getPosts() {

        const db = this.database();
        const postCol = db.collection('post');
        let res = await postCol.orderBy("postTimeStamp", "desc").get();
        let postList = res.data;

        let imageIdList = [];

        postList.forEach(post => {

            post.images.forEach(img => {
                imageIdList.push(img)
            })

        })

        let imgUrlList = await wf.getModule('cloudApi').getFilesUrl(imageIdList)

        let index = 0

        postList.forEach(post => {

            post.images.forEach((imgId, i) => {
                if (imgId === imgUrlList[index].fileID) {

                    // 将cloudId置换图片url
                    post.images[i] = imgUrlList[index].url
                }
                index += 1;

            })

        })
        // console.log('获取最新微博列表', postList, imgUrlList);

        return postList
    },

    deletePost(id) {
        const db = this.database();
        const postCol = db.collection('post');
        return postCol.doc(id).remove()
    },

    async updatePostLikes(id, data) {
        const db = this.database();
        const postCol = db.collection('post');
        const res = await postCol.doc(id).get()
        const target = res.data[0]
        const user = data

        const isLiked = target.likes.findIndex(likeUser => {
            return likeUser.uid === user.uid
        })

        let message = ''

        if (isLiked >= 0) {
            message = '取消点赞'
            target.likes.splice(isLiked, 1)
        } else {
            message = '添加点赞'

            const req = {
                uid: user.uid,
                userInfo: user,
                likeTimeStamp: new Date().getTime()
            }

            target.likes.push(req)
        }
        console.log('updatePostLikes-', message);

        const addRes = await postCol.doc(id).update({
            likes: target.likes
        })

        return addRes
    }
};
